package com.good.serviceImp;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import com.good.service.EmailService;

@Service("emailServiceImpl")
public class EmailServiceImpl implements EmailService {
	@Resource(name = "emailTemplate")
	private SimpleMailMessage emailTemplate;
	@Resource(name = "javaMailSender")
	private JavaMailSenderImpl javaMailSender;

	@Override
	public void sendMail(String toUsername ,String toEmailName, String myName) {
		String fromEmail = emailTemplate.getFrom();
		//String[] toEmail = emailTemplate.getTo();
		String emailSubject = emailTemplate.getSubject();
		String emailBody = String
				.format(emailTemplate.getText(), toUsername, myName);

		MimeMessage mimeMessage = javaMailSender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

			helper.setFrom(fromEmail);
			helper.setTo(toEmailName);
			// helper.setTo(toEmail);
			helper.setSubject(emailSubject);
			helper.setText(emailBody);

			/*
			 * uncomment the following lines for attachment FileSystemResource
			 * file = new FileSystemResource("attachment.jpg");
			 * helper.addAttachment(file.getFilename(), file);
			 */

			javaMailSender.send(mimeMessage);
			System.out.println("Mail sent successfully.");
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void sendSimpleEmail(String toUsername, String toEmail) {
		SimpleMailMessage message=new SimpleMailMessage();
		message.setFrom("jiejie531526@163.com");
		message.setTo(toEmail);
		message.setSubject("subject");
		message.setText("我的文本信息");
		javaMailSender.send(message);
	}
	public void sendMoreEmail(){
		MimeMessage mimeMessage=javaMailSender.createMimeMessage();
		MimeMessageHelper mmh;
		try {
			mmh=new MimeMessageHelper(mimeMessage,true);
			mmh.setFrom("jiejie531526@live.com");
			mmh.setTo("531526205@qq.com");
			mmh.setSubject("主题");
			/*mmh.setText("内容");
			FileSystemResource myImage=new FileSystemResource("/你的资源地址");
			mmh.addAttachment("资源名字", myImage);*/
			mmh.setText("<html><body>随便写，注意图片地址<img src='cid:logo'></body></html>",true);
			ClassPathResource imge=new ClassPathResource("图片名字.jpg");
			mmh.addInline("logo", imge);
			javaMailSender.send(mimeMessage);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		
	}
}
